//鼠标拖拽物体
using System.Collections;
using DG.Tweening;
using UnityEngine;

public class DragObjectByMouse : MonoBehaviour
{
    //把初始化位置存储起来
    private Vector3 _originPosition;
    private Tweener _tweener;

    private void Start()
    {
        _originPosition = transform.position;
        //初始化旋转360度动画，设置匀速播放动画，在播放状态时一直播放动画
        //默认动画不播放
        _tweener = transform.DOLocalRotate(Vector3.up * 360, 4, RotateMode.LocalAxisAdd)
            .SetEase(Ease.Linear).SetLoops(-1);
        _tweener.Pause();
    }

    IEnumerator OnMouseDown()
    {
        Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);//三维物体坐标转屏幕坐标
        //将鼠标屏幕坐标转为三维坐标，再计算物体位置与鼠标之间的距离
        var offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
        print("down");
        _tweener.Play();    //鼠标点击下，开始播放动画
        while (Input.GetMouseButton(0))
        {
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
            var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
            transform.position = curPosition;
            yield return new WaitForFixedUpdate();
        }
    }

    private void OnMouseUp()
    {
        transform.position = _originPosition;
        //鼠标抬起停止播放动画，并把它位置置零
        _tweener.Pause();
        transform.rotation =new Quaternion(0,0,0,0);
    }
}
